﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Lavka.Models;

namespace Lavka.Core
{
    public static class ImportHelper
    {
        public static List<PriceProduct> GetProductsFromPrice(string rawPrice)
        {
            List<PriceProduct> priceProducts = new List<PriceProduct>();
            string[] productSplitter = new []{"\r\n"};
            string[] products = rawPrice.Split(productSplitter, StringSplitOptions.RemoveEmptyEntries);
            foreach (var product in products)
            {
                try
                {
                    var parametersSplitter = new[] { ";"};
                    var trimmers = new[] { ' ', '"','\"'};
                    string[] parameters = product.Split(parametersSplitter, StringSplitOptions.None);
                    string firstWord = parameters[0].Split(trimmers)[0];
                    if (Regex.IsMatch(firstWord, @"\d"))
                    {
                        var reference = firstWord.TrimEnd(trimmers).TrimStart(trimmers);
                        var name = parameters[0].TrimStart(firstWord.ToCharArray()).TrimEnd(trimmers).TrimStart(trimmers);
                        var price = Convert.ToDecimal(parameters[2]);
                        bool availability = false;

                        int number;
                        Int32.TryParse(parameters[3], out number);
                        if (number > 0) availability = true;
                        var priceProduct = new PriceProduct
                                                {
                                                    Reference = reference,
                                                    Name = name,
                                                    Price = price,
                                                    Availability = availability
                                                };
                        priceProducts.Add(priceProduct);
                    }
                }
                catch{}
            }
            return priceProducts.ToList();
        }
    }
}